import random
import time

import pyautogui
import cv2
import win32api
import win32con
from PIL import ImageGrab

import find_image
class Picker:
    left, top, right, bottom = [0, 0, 0, 0];
    hwnd = -1
    def __init__(self, left, top, right, bottom, hwnd):
        self.left = left if (left >= 0) else 0
        self.top = top if (top >= 0) else 0
        self.right = right if (right <= 1800) else 1800
        self.bottom = bottom if bottom <= 1000 else 1000
        self.hwnd = hwnd
    def pick(self, number):
        times = 1
        while times > 0:
                minLocal = self.check(number)
                if (minLocal == -1 or (minLocal[1] > 399 or minLocal[1] < 320 or minLocal[0] > 680 or minLocal[0] < 600)):
                    self.around(number)
                    time.sleep(3)
                    times -= 1
                else:
                    break
        if times == -1:
            print("没找到采药按钮")
            return
        long_position = win32api.MAKELONG(minLocal[0] + 35 , minLocal[1] + 10 )#模拟鼠标指针 传送到指定坐标
        win32api.SendMessage(self.hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, long_position)#模拟鼠标按下
        time.sleep(0.2)
        win32api.SendMessage(self.hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, long_position)#模拟鼠标弹起
        time.sleep(5.1 + 1 * random.randrange(20, 100) / 100.0)
    def check(self, number):
        ImageGrab.grab((self.left, self.top, self.right, self.bottom)).save("static/images/img_Winapi.bmp")
        grassImg = cv2.imread("static/images/pick_grass" + str(number) + ".png");
        windowImg = cv2.imread("static/images/img_Winapi.bmp");
        minLocal = find_image.fastFind(windowImg, grassImg);
        return minLocal
    def around(self, number):
        win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 68,0)
        time.sleep(0.1 + self.rand())
        win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, 68,0)
        time.sleep(0.1 + random.randrange(0, 10) / 100.0)
        win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 65,0)
        time.sleep(0.1 + self.rand())
        win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, 65,0)
        time.sleep(0.1 + self.rand())
        rightTime = random.randrange(20, 30) / 100.0
        win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 87,0)
        time.sleep(0.1 + self.rand())
        win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, 87,0)
        time.sleep(0.1 + random.randrange(0, 10) / 100.0)
        win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 83,0)
        time.sleep(0.1 + self.rand())
        win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, 83,0)
        time.sleep(0.1 + self.rand())
    def rand(self):
        return random.randrange(0, 10) / 100.0
